package com.example.teacher_app.vm.base;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModel;
import androidx.viewbinding.ViewBinding;


public abstract class BaseFragment<V extends ViewBinding, M extends ViewModel> extends Fragment {

    protected V binding;
    protected M mViewModel;
    protected boolean isInit = false;
    protected boolean isLoad = false;
    protected boolean isOnce = true;

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mViewModel = setViewModel();
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        isCanLoadData();
        isInit = true;
        binding = setContentView(inflater, container);
        return binding.getRoot();
    }


    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        isCanLoadData();
    }


    private void isCanLoadData() {
        if (!isInit) {
            return;
        }
        if (getUserVisibleHint()) {
            onVisible();
            isLoad = true;
            if (isOnce) {
                onFirstLoad();
                isOnce = false;
            }
        } else {
            if (isLoad) {
                onInvisible();
            }
        }
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        isInit = false;
        isLoad = false;
    }


    protected abstract V setContentView(LayoutInflater inflater, @Nullable ViewGroup container);

    protected abstract M setViewModel();


    protected abstract void onVisible();

    protected abstract void onFirstLoad();

    protected void onInvisible() {

    }
}